import axios from 'axios'

const API_URL = 'http://localhost:3001/api' // 确保这个地址与您的后端服务器地址匹配

export default {
  namespaced: true,
  
  state: {
    list: [],
    total: 0,
    loading: false
  },

  mutations: {
    SET_MOVIES(state, movies) {
      state.list = movies
    },
    SET_TOTAL(state, total) {
      state.total = total
    },
    SET_LOADING(state, loading) {
      state.loading = loading
    }
  },

  actions: {
    // 获取电影列表
    async fetchMovies({ commit }, { page, pageSize }) {
      commit('SET_LOADING', true)
      try {
        console.log('正在获取电影列表...')
        const response = await axios.get(`${API_URL}/movies`, {
          params: {
            start: (page - 1) * pageSize,
            count: pageSize
          }
        })
        console.log('获取到的电影数据:', response.data)
        commit('SET_MOVIES', response.data)
        commit('SET_TOTAL', response.data.length)
      } catch (error) {
        console.error('获取电影列表失败:', error)
        // 如果API调用失败，使用模拟数据
        const mockData = [
          {
            id: 1,
            title: '示例电影1',
            director: '导演1',
            release_date: '2024-01-01',
            average_rating: 8.5,
            genres: ['动作', '冒险'],
            image_url: 'https://example.com/movie1.jpg',
            summary: '这是一部示例电影'
          },
          {
            id: 2,
            title: '示例电影2',
            director: '导演2',
            release_date: '2024-01-02',
            average_rating: 7.5,
            genres: ['喜剧', '爱情'],
            image_url: 'https://example.com/movie2.jpg',
            summary: '这是另一部示例电影'
          }
        ]
        commit('SET_MOVIES', mockData)
        commit('SET_TOTAL', mockData.length)
      } finally {
        commit('SET_LOADING', false)
      }
    },

    // 添加电影
    async addMovie({ dispatch }, movieData) {
      try {
        console.log('正在添加电影:', movieData)
        const response = await axios.post(`${API_URL}/movies`, movieData)
        console.log('添加电影成功:', response.data)
        return true
      } catch (error) {
        console.error('添加电影失败:', error)
        throw error
      }
    },

    // 更新电影
    async updateMovie({ dispatch }, movieData) {
      try {
        console.log('正在更新电影:', movieData)
        const response = await axios.put(`${API_URL}/movies/${movieData.id}`, movieData)
        console.log('更新电影成功:', response.data)
        return true
      } catch (error) {
        console.error('更新电影失败:', error)
        throw error
      }
    },

    // 删除电影
    async deleteMovie({ dispatch }, movieId) {
      try {
        console.log('正在删除电影:', movieId)
        const response = await axios.delete(`${API_URL}/movies/${movieId}`)
        console.log('删除电影成功:', response.data)
        return true
      } catch (error) {
        console.error('删除电影失败:', error)
        throw error
      }
    }
  }
} 